import React, { useState } from "react";
import { message } from 'antd';
import { history } from 'umi';
import config from "../../config/config";
import * as loginService from './loginService';
import { useGlobalShare } from "../../models/globalShare";

export function useLoginState() {

    const { currentUser, setCurrentUser } = useGlobalShare();
    const [authImageCode, setAauthImageCode] = useState({});

    const load_auth_code = (params) => {
        loginService.getAuthCode(params).then(res => {
            if (res.code == 200) {
                setAauthImageCode(res.data);
            }
        });
    }

    const loginUser = (params) => {
        loginService.selectSystemUser(params).then(res => {
            if (res.code == 200) {
                if (!res.data) {
                    message.error("账号密码有误");
                    return;
                }

                const pathname = config.menu_side["home"][0].link;
                history.push({ pathname, state: { currentUser: res.data }});
                window.location.pathname = pathname;

                setCurrentUser(res.data);
                sessionStorage.setItem("currentUser", JSON.stringify(res.data));
            }
        });
    }

    return {
        authImageCode, currentUser, setCurrentUser, load_auth_code, loginUser
    };
}
